<template>
  <div class="patrol-task-container">
    <div class="search-bar">
      <div class="search-section">
        <div class="search-inputs">
          <el-select
            v-model="queryParams.communityId"
            placeholder="请选择社区"
            clearable
            class="search-item"
            @change="handleCommunityChange"
          >
            <el-option
              v-for="item in communityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-select
            v-model="queryParams.taskStatus"
            placeholder="请选择任务状态"
            clearable
            class="search-item"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-input
            v-model="queryParams.searchText"
            placeholder="请输入巡更计划名称"
            class="search-item search-input"
            @keyup.enter.native="searchData"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchData"
            ></el-button>
          </el-input>
          <div class="search-buttons">
            <el-button
              type="info"
              plain
              icon="el-icon-refresh"
              @click="resetSearch"
              >重置</el-button
            >
            <el-button type="primary" icon="el-icon-search" @click="searchData"
              >搜索</el-button
            >
          </div>
        </div>
      </div>
      <div class="add-section">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAddTask"
          >添加任务</el-button
        >
      </div>
    </div>

    <div class="table-container">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column label="序号" width="80" align="center" fixed>
          <template slot-scope="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        
        <el-table-column
          prop="communityName"
          label="所属社区"
          width="120"
          align="center"
        ></el-table-column>
        
        <el-table-column
          prop="planName"
          label="巡更计划"
          width="150"
          align="center"
        ></el-table-column>
        
        <el-table-column
          prop="taskDate"
          label="执行日期"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            {{ formatDate(scope.row.taskDate) }}
          </template>
        </el-table-column>
        
        <el-table-column
          label="计划时间"
          width="310"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.plannedStartTime }} 至 {{ scope.row.plannedEndTime }}
          </template>
        </el-table-column>
        
        <el-table-column
          label="实际时间"
          width="310"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.actualStartTime && scope.row.actualEndTime ? 
               scope.row.actualStartTime + ' 至 ' + scope.row.actualEndTime : 
               scope.row.actualStartTime ? scope.row.actualStartTime + ' - 进行中' : '未开始' }}
          </template>
        </el-table-column>
        
        <el-table-column
          prop="executorName"
          label="执行人员"
          width="100"
          align="center"
        ></el-table-column>
        
        <el-table-column
          prop="completionRate"
          label="完成率"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.completionRate ? scope.row.completionRate + '%' : '0%' }}
          </template>
        </el-table-column>
        
        <el-table-column
          prop="taskStatus"
          label="任务状态"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span :class="getStatusClass(scope.row.taskStatus)">
              {{ getStatusText(scope.row.taskStatus) }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" min-width="342" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-document"
              @click="handleDetail(scope.row)"
            >详情</el-button>
            <el-button
              v-if="scope.row.taskStatus === 0"
              type="success"
              size="mini"
              icon="el-icon-video-play"
              @click="handleStart(scope.row)"
            >开始</el-button>
            <el-button
              v-if="scope.row.taskStatus === 1"
              type="warning"
              size="mini"
              icon="el-icon-video-pause"
              @click="handlePause(scope.row)"
            >暂停</el-button>
            <el-button
              v-if="scope.row.taskStatus === 3"
              type="success"
              size="mini"
              icon="el-icon-video-play"
              @click="handleResume(scope.row)"
            >继续</el-button>
            <el-button
              v-if="[1, 3].includes(scope.row.taskStatus)"
              type="info"
              size="mini"
              icon="el-icon-finished"
              @click="handleEnd(scope.row)"
            >结束</el-button>
            <el-button
              v-if="[0, 1, 3].includes(scope.row.taskStatus)"
              type="danger"
              size="mini"
              icon="el-icon-close"
              @click="handleCancel(scope.row)"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 详情对话框 -->
    <el-dialog title="巡更任务详情" :visible.sync="detailDialogVisible" width="80%">
      <div v-loading="detailLoading">
        <div class="task-info">
          <div class="info-row">
            <div class="info-item">
              <span class="label">巡更计划：</span>
              <span class="value">{{ currentTask.planName }}</span>
            </div>
            <div class="info-item">
              <span class="label">所属社区：</span>
              <span class="value">{{ currentTask.communityName }}</span>
            </div>
            <div class="info-item">
              <span class="label">执行日期：</span>
              <span class="value">{{ currentTask.taskDate }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="label">计划时间：</span>
              <span class="value">{{ currentTask.plannedStartTime }} - {{ currentTask.plannedEndTime }}</span>
            </div>
            <div class="info-item">
              <span class="label">实际时间：</span>
              <span class="value">
                {{ currentTask.actualStartTime && currentTask.actualEndTime ? 
                   currentTask.actualStartTime + ' - ' + currentTask.actualEndTime : 
                   currentTask.actualStartTime ? currentTask.actualStartTime + ' - 进行中' : '未开始' }}
              </span>
            </div>
            <div class="info-item">
              <span class="label">执行人员：</span>
              <span class="value">{{ currentTask.executorName }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="label">任务状态：</span>
              <span class="value" :class="getStatusClass(currentTask.taskStatus)">
                {{ getStatusText(currentTask.taskStatus) }}
              </span>
            </div>
            <div class="info-item"></div>
            <div class="info-item"></div>
          </div>
        </div>

        <div class="point-list">
          <h3>巡更点位列表</h3>
          <el-table :data="pointList" border style="width: 100%">
            <el-table-column label="序号" width="60" align="center">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="pointName" label="巡更点名称" width="150" align="center"></el-table-column>
            <el-table-column prop="locationCode" label="位置编号" width="120" align="center"></el-table-column>
            <el-table-column prop="buildingName" label="位置" width="180" align="center"></el-table-column>
            <el-table-column prop="categoryName" label="巡更类别" width="120" align="center"></el-table-column>
            <el-table-column prop="checkTime" label="打卡时间" width="180" align="center">
              <template slot-scope="scope">
                {{ scope.row.checkTime || '未打卡' }}
              </template>
            </el-table-column>
            <el-table-column prop="result" label="巡检结果" width="150" align="center">
              <template slot-scope="scope">
                {{ scope.row.result || '暂无结果' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询参数
      queryParams: {
        communityId: null,
        taskStatus: null,
        searchText: "",
        pageNum: 1,
        pageSize: 10
      },
      // 社区选项
      communityOptions: [],
      // 状态选项
      statusOptions: [
        { value: 0, label: "未开始" },
        { value: 1, label: "进行中" },
        { value: 2, label: "已完成" },
        { value: 3, label: "已暂停" },
        { value: 4, label: "已取消" },
        { value: 5, label: "执行失败" }
      ],
      // 表格数据
      tableData: [],
      // 总数据量
      total: 0,
      // 加载状态
      loading: false,
      // 详情对话框可见性
      detailDialogVisible: false,
      // 详情加载状态
      detailLoading: false,
      // 当前任务
      currentTask: {},
      // 巡更点位列表
      pointList: []
    };
  },

  created() {
    // 初始加载数据
    this.loadCommunityOptions();
    this.fetchData();
  },

  methods: {
    // 加载社区选项
    loadCommunityOptions() {
      this.loading = true;
      this.$axios
        .get("api/infrastructure-server/community/queryAll")
        .then(response => {
          if (response.data && response.data.code === 200) {
            this.communityOptions = response.data.data.map(item => {
              return { value: item.id, label: item.name };
            });
          } else {
            this.$message.error(response.data.message || "获取社区列表失败");
          }
        })
        .catch(error => {
          console.error("获取社区列表错误:", error);
          this.$message.error("获取社区列表错误");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 获取巡更任务数据
    fetchData() {
      this.loading = true;
      // 构建查询参数
      const params = {
        ...this.queryParams
      };
      
      // 如果有搜索文本，添加到查询参数
      if (this.queryParams.searchText) {
        params.planName = this.queryParams.searchText;
      }
      
      this.$axios
        .post("api/patrol-server/patrolTask/queryByPageInfo", params)
        .then(response => {
          if (response.data && response.data.code === 200) {
            const { records, total } = response.data.data;
            this.tableData = records || [];
            this.total = total || 0;
          } else {
            this.$message.error(response.data.message || "获取巡更任务列表失败");
          }
        })
        .catch(error => {
          console.error("获取巡更任务列表出错:", error);
          this.$message.error("获取巡更任务列表出错");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 社区选择变更
    handleCommunityChange() {
      this.queryParams.pageNum = 1;
      this.fetchData();
    },

    // 搜索数据
    searchData() {
      this.queryParams.pageNum = 1;
      this.fetchData();
    },

    // 重置搜索
    resetSearch() {
      this.queryParams = {
        communityId: null,
        taskStatus: null,
        searchText: "",
        pageNum: 1,
        pageSize: 10
      };
      this.fetchData();
    },

    // 处理页面大小变化
    handleSizeChange(size) {
      this.queryParams.pageSize = size;
      this.fetchData();
    },

    // 处理页码变化
    handleCurrentChange(page) {
      this.queryParams.pageNum = page;
      this.fetchData();
    },

    // 获取状态样式类
    getStatusClass(status) {
      const statusMap = {
        0: 'status-pending',
        1: 'status-progress',
        2: 'status-completed',
        3: 'status-paused',
        4: 'status-cancelled',
        5: 'status-failed'
      };
      return statusMap[status] || '';
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '未开始',
        1: '进行中',
        2: '已完成',
        3: '已暂停',
        4: '已取消',
        5: '执行失败'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取巡更点状态样式类
    getPointStatusClass(status) {
      const statusMap = {
        0: 'point-pending',
        1: 'point-completed',
        2: 'point-overdue'
      };
      return statusMap[status] || '';
    },

    // 获取巡更点状态文本
    getPointStatusText(status) {
      const statusMap = {
        0: '未打卡',
        1: '已打卡',
        2: '逾期'
      };
      return statusMap[status] || '未知状态';
    },

    // 查看详情
    handleDetail(row) {
      this.currentTask = { ...row };
      this.detailDialogVisible = true;
      this.detailLoading = true;
      
      // 获取任务详情和巡更点列表
      this.$axios
        .get(`api/patrol-server/patrolTask/queryPointByTaskId?taskId=${row.taskId}`)
        .then(response => {
          if (response.data && response.data.code === 200) {
            this.pointList = response.data.data || [];
          } else {
            this.$message.error(response.data.message || "获取巡更任务详情失败");
          }
        })
        .catch(error => {
          console.error("获取巡更任务详情出错:", error);
          this.$message.error("获取巡更任务详情出错");
        })
        .finally(() => {
          this.detailLoading = false;
        });
    },

    // 开始任务
    handleStart(row) {
      this.$confirm('确认开始此巡更任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios
          .get(`api/patrol-server/patrolTask/start/${row.taskId}`)
          .then(response => {
            if (response.data && response.data.code === 200) {
              this.$message.success("任务已开始");
              this.fetchData();
            } else {
              this.$message.error(response.data.message || "开始任务失败");
            }
          })
          .catch(error => {
            console.error("开始任务出错:", error);
            this.$message.error("开始任务出错");
          });
      }).catch(() => {
        // 取消操作
      });
    },

    // 暂停任务
    handlePause(row) {
      this.$confirm('确认暂停此巡更任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios
          .get(`api/patrol-server/patrolTask/pause/${row.taskId}`)
          .then(response => {
            if (response.data && response.data.code === 200) {
              this.$message.success("任务已暂停");
              this.fetchData();
            } else {
              this.$message.error(response.data.message || "暂停任务失败");
            }
          })
          .catch(error => {
            console.error("暂停任务出错:", error);
            this.$message.error("暂停任务出错");
          });
      }).catch(() => {
        // 取消操作
      });
    },

    // 继续任务
    handleResume(row) {
      this.$confirm('确认继续此巡更任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios
          .get(`api/patrol-server/patrolTask/resume/${row.taskId}`)
          .then(response => {
            if (response.data && response.data.code === 200) {
              this.$message.success("任务已继续");
              this.fetchData();
            } else {
              this.$message.error(response.data.message || "继续任务失败");
            }
          })
          .catch(error => {
            console.error("继续任务出错:", error);
            this.$message.error("继续任务出错");
          });
      }).catch(() => {
        // 取消操作
      });
    },

    // 结束任务
    handleEnd(row) {
      this.$confirm('确认结束此巡更任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios
          .get(`api/patrol-server/patrolTask/end/${row.taskId}`)
          .then(response => {
            if (response.data && response.data.code === 200) {
              this.$message.success("任务已结束");
              this.fetchData();
            } else {
              this.$message.error(response.data.message || "结束任务失败");
            }
          })
          .catch(error => {
            console.error("结束任务出错:", error);
            this.$message.error("结束任务出错");
          });
      }).catch(() => {
        // 取消操作
      });
    },

    // 取消任务
    handleCancel(row) {
      this.$confirm('确认取消此巡更任务? 此操作不可恢复', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        this.$axios
          .get(`api/patrol-server/patrolTask/cancel/${row.taskId}`)
          .then(response => {
            if (response.data && response.data.code === 200) {
              this.$message.success("任务已取消");
              this.fetchData();
            } else {
              this.$message.error(response.data.message || "取消任务失败");
            }
          })
          .catch(error => {
            console.error("取消任务出错:", error);
            this.$message.error("取消任务出错");
          });
      }).catch(() => {
        // 取消操作
      });
    },

    // 添加任务
    handleAddTask() {
      // 实现添加任务的逻辑
      console.log("添加任务");
      this.$router.push("/patrolTaskAdd");
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      try {
        const dateObj = new Date(date);
        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      } catch (e) {
        return date;
      }
    },
  },
}
</script>

<style scoped>
.patrol-task-container {
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-section {
  flex: 1;
}

.search-inputs {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-item {
  margin-right: 15px;
  margin-bottom: 10px;
  width: 180px;
}

.search-input {
  width: 220px;
}

.search-buttons {
  display: inline-block;
}

.add-section {
  display: flex;
  align-items: flex-start;
}

.add-button {
  margin-left: 15px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 状态样式 */
.status-pending {
  color: #909399;
}

.status-progress {
  color: #409EFF;
}

.status-completed {
  color: #67C23A;
}

.status-paused {
  color: #E6A23C;
}

.status-cancelled {
  color: #F56C6C;
}

.status-failed {
  color: #F56C6C;
}

.point-pending {
  color: #909399;
}

.point-completed {
  color: #67C23A;
}

.point-overdue {
  color: #F56C6C;
}

/* 详情对话框样式 */
.task-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: center;
}

.label {
  font-weight: bold;
  width: 100px;
  text-align: right;
  margin-right: 10px;
}

.value {
  flex: 1;
}

.point-list {
  margin-top: 20px;
}

.point-list h3 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}
</style>